import React, { useEffect, useState, useCallback } from 'react';
import styles from './index.less';

const Captcha: React.FC<any> = ({ className,uuidCode, onClick }) => {
  const [count, setCount] = useState(0);
  const [loading, setloading] = useState(false);
  useEffect(() => {
    const timer = setTimeout(() => {
      if (count > 0) {
        setCount((c: number) => c - 1); // 在这不依赖于外部的 `count` 变量
      }
    }, 1000);
    return () => {
      clearTimeout(timer);
    };
  }, [count]); // 只有count发生变化时触发
  const sendCode = async () => {
    if (onClick) {
      
      // if ((await onClick()) !== false) {
      //   setCount(60);
      // }
      // 通过回调开启倒计时
      setloading(true)
      onClick(()=>{
        setCount(60)
        setloading(false)
      })
    } else {
      setCount(60);
    }
  }; // 缓存方法，防止多次生成浪费内存
  return (
    <div className={className}>
      {count > 0 ? (
        <span className={styles.badge} style={{ color: '#999' }}>
          重新获取 {count}s
        </span>
      ) : (
        <span onClick={sendCode} className={styles.badge}>
          {loading?'短信发送中':'获取验证码'}
        </span>
      )}
    </div>
  );
};

export default Captcha;
